package cn.diancan.util;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream; 

public class CutImg {
	
	public static String GIF = "gif";
	public static String JPG = "jpg";
	public static String PNG = "png";
	public static String BMP = "bmp";
	//public static String TIF = "tiff";//无法压缩 “II”
	
	   ///* //calc1.0
    /*  if(height>reader.getHeight(0)  || width>reader.getWidth(0)){
      	if(height>reader.getHeight(0)  && width>reader.getWidth(0)){ 
      		width=reader.getWidth(0);
           	height=reader.getHeight(0);
      	}else if(height>reader.getHeight(0)){ 
           	height=reader.getHeight(0);
           	x=(reader.getWidth(0)-width)/2;
          }else if(width>reader.getWidth(0)){
          	width=reader.getWidth(0);
           	y=(reader.getHeight(0)-height)/2;
          }
      }else{
      	if(width== height){//要正方形
          	if(reader.getHeight(0)>reader.getWidth(0)){ 
          		y=(reader.getHeight(0)-reader.getWidth(0))/2;
               	width=reader.getWidth(0);
               	height=reader.getWidth(0); 
               }else{
               	x=(reader.getWidth(0)-reader.getHeight(0))/2;
               	width=reader.getHeight(0);
               	height=reader.getHeight(0);
               }
      	}else{
      		Integer widthRate =  reader.getWidth(0) / width; 
				 	Integer heightRate =  reader.getHeight(0) / height ; 
				 // 根据缩放比率大的进行缩放控制 
				 	if(widthRate>heightRate){//宽相差大
				 		width= (width*heightRate);
				 	    height=reader.getHeight(0);
				 	    x=(reader.getWidth(0)-width)/2;
				 	}else{
				 		height=(height*widthRate);
				 		width=reader.getWidth(0);
				 		y=(reader.getHeight(0)-height)/2;
				 	}
      	}
      }  */
      //*/计算(需求)
	
	 //calc2.0
    /*Double widthRate =  (double)reader.getWidth(0) / (double)width; 
    Double heightRate =  (double)reader.getHeight(0) / (double)height ; 
	// 根据缩放比率大的进行缩放控制 
	if(widthRate>heightRate){//宽相差大
	 		width= (int)(width*heightRate);
	 	    height=reader.getHeight(0);
	 	    x=(reader.getWidth(0)-width)/2;
	}else{
	 		height=(int)(height*widthRate);
	 		width=reader.getWidth(0);
	 		y=(reader.getHeight(0)-height)/2;
	}*/
 
	
	/**
	 * 
	 * @param input
	 * @param out
	 * @param width
	 * @param height
	 * @param imageType
	 * @throws IOException 
	 * @throws Exception
	 */
    public static boolean cutImage( String inputFileName, String outputFileName, int width, int height,String imageType) throws Exception{
        ImageInputStream imageStream = null;
        try {
        	int x=0;
        	int y=0;  
        	InputStream input=new FileInputStream(inputFileName);
        	OutputStream out=new FileOutputStream(outputFileName);
            Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageType);
            ImageReader reader = readers.next();  
            imageStream = ImageIO.createImageInputStream(input);
            reader.setInput(imageStream, true);
            ImageReadParam param = reader.getDefaultReadParam();  
            if(height>=reader.getHeight(0)  && width>=reader.getWidth(0)){//刚好原图一样大小 
          		return false;//不保存
          	}
            boolean isNeddCompress=true;//是否需要压缩
            if(height>=reader.getHeight(0)  || width>=reader.getWidth(0)){//图片的宽高 小于或等于需要的宽高 
            	if(height>=reader.getHeight(0)){
                   	height=reader.getHeight(0);
                   	x=(reader.getWidth(0)-width)/2;
                }else if(width>=reader.getWidth(0)){
                  	width=reader.getWidth(0);
                   	y=(reader.getHeight(0)-height)/2;
                }
            	isNeddCompress=false;
            }else{
              	if(width== height){//要正方形
                  	   if(reader.getHeight(0)>reader.getWidth(0)){ 
                  			y=(reader.getHeight(0)-reader.getWidth(0))/2;
                  			width=reader.getWidth(0);
                  			height=reader.getWidth(0); 
                       }else{
                       		x=(reader.getWidth(0)-reader.getHeight(0))/2;
                       		width=reader.getHeight(0);
                       		height=reader.getHeight(0);
                       }
              	}else{
              		double widthRate = (double) reader.getWidth(0) /(double) width; 
              		double heightRate = (double) reader.getHeight(0) / (double)height ; 
        			// 根据缩放比率大的进行缩放控制 
        			if(widthRate>heightRate){//宽相差大
        				width= (int)(width*heightRate);
        				height=reader.getHeight(0);
        				x=(reader.getWidth(0)-width)/2;
        			}else{
        				height=(int)(height*widthRate);
        				width=reader.getWidth(0);
        				y=(reader.getHeight(0)-height)/2;
        			}
              	}
           } 
           	
           Rectangle rect = new Rectangle(x, y, width, height);
           param.setSourceRegion(rect);
           BufferedImage bi = reader.read(0, param);
           ImageIO.write(bi,imageType, out);
           return isNeddCompress;
        }  finally {
            try {
            	if(null!=imageStream){
            		imageStream.close();
            	} 
			} catch (IOException e) { 
				e.printStackTrace();
			} 
        } 
    }
    /**
     * 检查是否是图片类型
     * @param inputFileName
     * @return
     * @throws Exception 
     */
    public static String checkImageType(String inputFileName) throws Exception{
    	try {
			InputStream input = new FileInputStream(inputFileName); 
			byte[] b = new byte[30];
			input.read(b);
			String typeSrc= new String(b);
			//
			if(typeSrc.indexOf("JFIF")!=-1){
				return CutImg.JPG;
			}else if(typeSrc.indexOf("GIF89")!=-1){
				return CutImg.GIF;
			}else if(typeSrc.indexOf("NG")!=-1){
				return CutImg.PNG;
			}else if(typeSrc.indexOf("BMV")!=-1){
				return CutImg.BMP;
			}
		}  catch (Exception e) { 
			e.printStackTrace();
		}
    	throw new Exception("无法识别的格式"); 
    }
    
    /**
     * 计算并切图
     * @param inputFileName
     * @param outputFileName
     * @param width
     * @param height
     * @return
     */
    public static boolean calcAndCutImage(String inputFileName,String outputFileName,int width,int height){
    	try {
			InputStream input = new FileInputStream(inputFileName); 
			byte[] b = new byte[30];
			input.read(b);
			String typeSrc= new String(b);
			String c="";
			if(typeSrc.indexOf("JFIF")!=-1){
				c=CutImg.JPG;
			}else if(typeSrc.indexOf("GIF89")!=-1){
				c=CutImg.GIF; 
			}else if(typeSrc.indexOf("NG")!=-1){
				c=CutImg.PNG;  
			}else if(typeSrc.indexOf("BMV")!=-1){
				c=CutImg.BMP;   
			}else{
				throw new Exception("无法识别的格式"); 
			}
			if(CutImg.cutImage(inputFileName,outputFileName, width,height,c)){
				CompressImg.compressPic(outputFileName, outputFileName,width,height,true,true);
				return true;
			}  
		}  catch (Exception e) { 
			e.printStackTrace();
		}
    	return false;
    }
    
    @Deprecated
    public static String calcAndCutImage(String inputFileName,int width,int height) throws Exception { 
    	String originalName = inputFileName.substring(inputFileName.lastIndexOf(System.getProperty("file.separator")) + 1);
    	int dotIndex= originalName.lastIndexOf(".");
    	String outputFileName="";
    	if(-1== dotIndex){
    		outputFileName=inputFileName.replace(originalName, originalName+"_"+width+"X"+height);//没有后缀名
    	}else{
        	outputFileName=inputFileName.replace(originalName, originalName.substring(0, dotIndex)+"_"+width+"X"+height+originalName.substring(dotIndex));
    	}
    	calcAndCutImage(inputFileName,outputFileName,width,height); 
    	File file= new File(outputFileName);
    	if (file.exists() && file.isFile()){//已经有了
    		 return outputFileName;
    	} 
    	if(calcAndCutImage(inputFileName,outputFileName,width,height)){
    		return outputFileName;
    	}
    	throw new Exception("失败");
    }
     
    
    public static void main(String[] args) throws Exception {
    	long l= System.currentTimeMillis(); 
    	int width=800,height=200; 
    	String inputFileName="d:/img_test/YMXXXX1000113-49131_800X200.jpg"; 
    	String inputFileName2="d:/img_test/YMXXXX1000113-49131_800X200c.jpg"; 
    	calcAndCutImage(inputFileName,inputFileName2, width, height);
        System.out.println(System.currentTimeMillis()-l);
    }
    
}


